package com.dimong.www.loan.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class AutoLoopViewPager extends ViewPager {
    private int startX;
    private int startY;

    private long time = 4000L;
    private Handler mHandler;

    public AutoLoopViewPager(Context paramContext) {
        super(paramContext);
        init();
    }

    public AutoLoopViewPager(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
        init();
    }

    private void setHandlerTime(long time) {
        this.mHandler.removeMessages(0);
        this.mHandler.sendEmptyMessageDelayed(0, time);
    }

    private void init() {
        this.mHandler = new RepeatHandler();
    }

    public final void onResume() {
        if ((getAdapter() == null) || (getAdapter().getCount() == 0)) {
            return;
        }
        setHandlerTime(this.time);
    }

    public final void onPause() {
        this.mHandler.removeMessages(0);
    }

    public final void setCurrentItem() {
        int i = getCurrentItem();
        if (i >= 3) {
            i = 0;
        } else {
            i++;
        }
        setCurrentItem(i);
    }

//	@Override
//	public boolean dispatchTouchEvent(MotionEvent ev) {
//		int i = getCurrentItem();
//		if (i >= 3) {
//			setCurrentItem(0);
//			return false;
//
//		} else {
//			return super.dispatchTouchEvent(ev);
//		}
//	}

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) ev.getX();
                startY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int dX = (int) (ev.getX() - startX);
                int dY = (int) (ev.getY() - startX);
                if (Math.abs(dX) > Math.abs(dY)) {//左右滑动
                    return true;
                } else {//上下滑动
                    return false;
                }
        }
        return super.onInterceptTouchEvent(ev);
    }

    private final class RepeatHandler extends Handler {
        private RepeatHandler() {
        }

        public final void handleMessage(Message message) {
            super.handleMessage(message);
            switch (message.what) {
                case 0:
                    AutoLoopViewPager.this.setCurrentItem();
                    mHandler.sendEmptyMessageDelayed(0, time);
                    break;
                default:
                    return;
            }
        }
    }
}
